package rickyGame.game.action
{
	import flash.geom.Point;
	import flash.geom.Vector3D;
	import flash.utils.getTimer;
	
	import ricky.game.Actor;
	import ricky.game.action.Act2D;
	import ricky.game.graphic.Graphic;
	import ricky.quadtree.Leaf;
	import ricky.quadtree.Quadtree;
	import ricky.utils.FrameManager;
	import ricky.utils.TimeServer;
	import ricky.utils.Utils;
	
	import ricky.game.Actor2D;
	import rickyGame.game.GameState;
	import rickyGame.game.Goods;
	import rickyGame.game.scene.Pathfinder;

	/**
	 * 按叶子移动
	 */
	public class MoveLeafAction extends Act2D
	{
		
		/**
		 * @param target:Pu 目标对象
		 * @param point:Leaf 目标点
		 * @path Array [leaf] 目标路径
		 */
		public function MoveLeafAction(actor:Actor2D,point:Leaf=null,path:Array=null)
		{
			super(actor);
			this._animProperty="run";
			this._path=path;
			_calcPoint=new Vector3D();
			if(point)
				_point=new Vector3D(point.x*Common.tileWidth,point.y*Common.tileHeight);;
			
			_type="MoveLeafAction";
		}
		
		override public function begin():void
		{
			_lastTime=TimeServer.now();
			if(this._path!=null)
				moveStep();
			calculateDirection();
			FrameManager.inst.addLogic(getActor())
		}
		
		override public function complete():void
		{
			if(_path!=null && this._path.length>0) //如果没到达目标
			{
				this._next=null;
				this._effectNext=null;
			}

			super.complete();
		}
		
		override	public function action(timeline:Number):void
		{
			var dot:Number=timeline-_lastTime;
			_lastTime=timeline;
			if(dot>1000)
			{
				var fps:int=FrameManager.inst.fps;
				_fpsDt=1000/fps;
			}
			if(this.isArrive())
			{
				if(this._path!=null && this._path.length>0) //如果有下一格子移动到下一格子
				{
					moveStep();
					calculateDirection();	
					return;
				}	
				if(this.actor.onArrive!=null)
					actor.onArrive(actor);
				this.complete();
				return;
			}
			else
			{
				//move移动	
				var v1:Number=_vx*_fpsDt;
				var v2:Number=_vy*_fpsDt;
				var x:Number=v1+this._actor.graphic.x;
				var y:Number=v2+this._actor.graphic.y;
				
				var gx:int=Actor2D(_actor).gridX;
				var gy:int=Actor2D(_actor).gridY;
				
				this._actor.graphic.x=Math.abs(_point.x - this._actor.graphic.x)<=Math.abs(v1)?_actor.graphic.x:x;//Math.abs(targetX - x) >=5?:targetX;
				this._actor.graphic.y=Math.abs(_point.y - this._actor.graphic.y)<=Math.abs(v2)?_actor.graphic.y:y;//Math.abs(targetY - y) >=5?:targetY;
//			
				var gx1:int=Actor2D(_actor).gridX;
				var gy1:int=Actor2D(_actor).gridY;
				
				if(this._actor.onMovingFun!=null)
					_actor.onMovingFun.call(null,_actor);
				
				if(gx!=gx1 || gy!=gy1)//格子位置改变
					onGridChange();
			}
			
		}
		
		override public function  end():void
		{
			FrameManager.inst.removeLogic(getActor());
			super.end();
		}

		
		protected function onGridChange():void
		{
			Actor2D(_actor).lastMorton=Actor2D(_actor).morton;
			Actor2D(_actor).calcMorton();
			var cl:Leaf=GameState.inst.scene.tree.getLeaf(Actor2D(_actor).lastMorton)  ;//GameWorld.tree.getLeaf(myMor);
			if(cl)
				cl.remove(_actor);
			cl=GameState.inst.scene.tree.push(_actor,Actor2D(_actor).morton) as Leaf;
			
			//寻找下一个格子
			
			var arr:int=cl.attr;
			if(arr==1)
				Graphic(_actor.graphic).alpha=0.5;
			else
				Graphic(_actor.graphic).alpha=1;
			
			if(_actor.stepFunction!=null)
				_actor.stepFunction.call(null,_actor);
		}
		
		override public function dispose():void
		{
			super.dispose();
			_path=null;
			_vx=NaN;
			_vy=NaN;
		}

//		
		//protected
		protected function moveToTarget():void
		{
			if(this._actor!=null)
			{
				_actor.graphic.x=_actor.graphic.x;
				_actor.graphic.y=_actor.graphic.y;
				calculateDirection();	
			}
		}
		
		
		/**
		 * 设置移动方向 方向向下为1 顺时针方向增加。
		 */
		protected function calculateDirection():void
		{
			var dx:Number=_point.x-this._actor.graphic.x;
			var dy:Number=_point.y-this._actor.graphic.y;
			var angle:Number=Math.atan2(dy,dx);//角度
			
			_vx=Math.cos(angle)*Actor2D(_actor).speed/1000;
			_vy=Math.sin(angle)*Actor2D(_actor).speed/1000;
			
			_calcPoint.x=_actor.graphic.x;
			_calcPoint.y=_actor.graphic.y;
			
//			_actor.velocity=_point.subtract(_calcPoint);
//			_actor.velocity.s
			if((angle<=0.17452 && angle>0) || (-0.17452<=angle && angle<0)  )//右  10 -10
				_dir=2;
			else if(angle>0.17452 && angle<= 1.39616)//右下10 80
				_dir=3;
			else if(angle>1.39616 && angle<=1.7452)//下80 100
				_dir=4;
			else if(angle>1.7452 && angle<=2.96684)//左下100 170
				_dir=5;
			else if(angle>2.96684  || angle<=-2.96684)//左 170 -170 
				_dir=6;
			else if(angle>-2.96684 && angle<=-1.7452)//左上 -170 -100; 
				_dir=7;
			else if(angle>-1.7452 && angle<=-1.39616)//上 -100 -80
				_dir=0;
			else if(angle>-1.39616 && angle<-0.17452)//右上 -80 -10
				_dir=1;
			
			Actor2D(_actor).direction=_dir;
			
			_actor.playAnimAct(_animProperty);
			
		}

		
		/**
		 * 是否移动到目标x,y
		 */
		protected function isArrive():Boolean
		{
			_calcPoint.x=_actor.graphic.x;
			_calcPoint.y=_actor.graphic.y;
			if(!_point ||  _point.subtract(_calcPoint).length<_radius)//if(x==this._currentObject.coordinate.x && this._currentObject.coordinate.y==y)
				return true;
			else
				return false;
		}
		
		/**
		 * 按步移动
		 */
		protected function moveStep():void
		{
			if(_path!=null && _path.length>=1)
			{
				var leaf:Leaf=_path.shift();//目标位置
				if(this.canWalk(leaf))
				{
					this._point=new Vector3D(leaf.x*Common.tileWidth+20,leaf.y*Common.tileHeight+15);
				}else
				{
//					 leaf=_path.shift();
					 var iswalk:Boolean=false;//=this.canWalk(leaf);
					 
					 while(!iswalk)//可走
					 {
						 leaf=_path.shift();
						 if(leaf)
							 iswalk=this.canWalk(leaf);
						 else
							 iswalk=true;
					 }
					 
					 if(!leaf)
					 {
						 this._point=new Vector3D(this._actor.graphic.x,this._actor.graphic.y);
						 return;
					 }
					 var tree:Quadtree=GameState.inst.scene.tree;
					 var me:Leaf=tree.getLeaf(Actor2D(_actor).morton)
					 var arr:Array=Pathfinder.findPath1(me,leaf,tree,Pathfinder.traversableAroundFunction,_actor.asType);
					if(arr)
					 _path=arr.concat(_path);
					 
					 leaf=_path.shift();
					this._point=new Vector3D(leaf.x*Common.tileWidth+20,leaf.y*Common.tileHeight+15);
				}
					
			}else
				this._point=new Vector3D(this._actor.graphic.x,this._actor.graphic.y);
		}
		
		/**
		 * 到达半径
		 */
		public function get radius():Number
		{
			return _radius;
		}
		
		public function set radius(value:Number):void
		{
			_radius = value;
		}
		
		/**
		 * 能否行走
		 */
		protected function canWalk(l:Leaf):Boolean
		{
			if(l.objects)
			{
				if(l.objects.length==0) //如果没有对象
					return true;
				
				for each(var actor:Actor in l.objects)
				{
					if(actor is Goods || actor.isDead==true) //如果是物品，或者已经死亡可以行走
						return true;
				}
				return false;
			}else
				return true;
		}

		//private 移动数组
		protected var _radius:Number=10;
		protected var _vx:Number=1.0;
		protected var _vy:Number=1.0;
		protected var _step:uint=0;//步数
		protected var _lastTime:Number=0;	
		protected var _tmpPath:Array;//小寻路数组用于被阻挡时候寻路
		protected var _fpsDt:Number=20;

//		protected var _actor:Pu;
		protected var _calcPoint:Vector3D;
		protected var _path:Array;
		protected var _point:Vector3D;
		protected var _dir:int;
	}
}